package com.blog.blog.service;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaService {

	private final RedissonClient redissonClient;
	private final SecureRandom random = new SecureRandom();

	public CaptchaService(RedissonClient redissonClient) {
		this.redissonClient = redissonClient;
	}

	private String keyFor(String token) {
		return "captcha:qa:" + token;
	}

	/**
	 * 生成简单问答验证码（加减法）。返回 token、question、ttl 秒。
	 */
	public Map<String, Object> generateQA(int ttlSeconds) {
		int a = 1 + random.nextInt(20);
		int b = 1 + random.nextInt(20);
		boolean plus = random.nextBoolean();
		int answer = plus ? (a + b) : Math.max(a - b, 0);
		String question = plus ? (a + " + " + b + " = ?") : (a + " - " + b + " = ?");

		String token = UUID.randomUUID().toString().replace("-", "");
		RBucket<String> bucket = redissonClient.getBucket(keyFor(token));
		bucket.set(String.valueOf(answer), ttlSeconds, TimeUnit.SECONDS);

		Map<String, Object> res = new HashMap<>();
		res.put("token", token);
		res.put("question", question);
		res.put("ttl", ttlSeconds);
		return res;
	}

	/**
	 * 校验验证码。成功时可选择一次性消费（删除）。
	 */
	public boolean validate(String token, String answer, boolean consume) {
		if (token == null || token.isBlank() || answer == null || answer.isBlank()) {
			return false;
		}
		RBucket<String> bucket = redissonClient.getBucket(keyFor(token));
		String expect = bucket.get();
		if (expect == null) return false;
		boolean ok = normalize(answer).equals(normalize(expect));
		if (ok && consume) {
			bucket.delete();
		}
		return ok;
	}

	private String normalize(String s) {
		return s.trim().toLowerCase();
	}
}


